﻿using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.View
{
    public partial class WikiPage : PhoneApplicationPage
    {
        private Category kategori;

        public WikiPage()
        {
            InitializeComponent();
        }

        private void ManageButton(Category category)
        {
            if (SavedUser.Instance.User != null)
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = true;
            else
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false;

            if (category != null)
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true;
            }
            else
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
            }
        }

        private void NavigateToFormPage(object selected)
        {
            FrameworkElement root = Application.Current.RootVisual as FrameworkElement;            
            root.DataContext = selected;
            Utility.GotoPage(this, "/View/WikiCategoryFormPage.xaml");
        }

        private void NavigateToList(object selected)
        {
            FrameworkElement root = Application.Current.RootVisual as FrameworkElement;
            root.DataContext = selected;
            Utility.GotoPage(this, "/View/WikiListPage.xaml");
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
            {
                ManageButton(null);
            }
            LoadWikiCategory(false, "");
        }

        private void LoadWikiCategory(bool search, string json)
        {
            kategori = null;

            string url = null;
            
            if(search)
                url = Config.Instance.CATEGORY_SERVICE_URL() + Config.FIND_ACTION_KEY;
            else
                url = Config.Instance.CATEGORY_SERVICE_URL() + Config.VIEW_ACTION_KEY;

            string urlformat = string.Format("{0}&{1}", url, Guid.NewGuid().ToString());
            Uri uri = new Uri(urlformat, UriKind.Absolute);

            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listWikiCategory_UploadStringCompleted);
            webClient.UploadStringAsync(uri, "POST", json);
        }

        private void listWikiCategory_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                {
                    MessageBox.Show("Message : " + e.Result);
                    return;
                }

                ObservableCollection<Category> list = JsonConvert.DeserializeObject<ObservableCollection<Category>>(e.Result);
                if (list.Count <= 0)
                {
                    kategori = new Category();
                    kategori.Kategori = "No wiki found";
                    list.Add(kategori);
                }
                listWikiCategory.ItemsSource = list;
                pivotWiki.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void listWikiCategory_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                kategori = (Category)e.AddedItems[0];

                ManageButton(kategori);
            }

        }

        private void DeleteCurrentCategory()
        {
            string json = null, url = null;

            if (kategori != null)
            {
                url = Config.Instance.CATEGORY_SERVICE_URL() + Config.DELETE_ACTION_KEY;
                json = JsonConvert.SerializeObject(kategori);

                Uri uri = new Uri(url, UriKind.Absolute);
                WebClient client = new WebClient();

                client.Encoding = Encoding.UTF8;
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

                client.UploadStringCompleted += new UploadStringCompletedEventHandler(deleteWikicategory_UploadStringCompleted);

                try
                {
                    client.UploadStringAsync(uri, "POST", json);
                }
                catch (Exception) { }
            }
        }

        private void deleteWikicategory_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                MessageBox.Show("Message : " + e.Result);
                if (e.Result.Contains("Success"))
                    LoadWikiCategory(false, "");
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            ManageButton(null);
            LoadWikiCategory(false, "");
        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            pivotWiki.SelectedIndex = 1;
        }

        private void buttonSearch_Click(object sender, RoutedEventArgs e)
        {
            if (textBoxKeyword.Text.Length < 1)
            {
                MessageBox.Show("Keyword is empty.");
                return;
            }

            Category find = new Category();
            find.Kategori = textBoxKeyword.Text;
            LoadWikiCategory(true, JsonConvert.SerializeObject(find));
        }

        private void detailButton_Click(object sender, EventArgs e)
        {
            NavigateToList(kategori);
        }

        private void menuAdd_Click(object sender, EventArgs e)
        {
            NavigateToFormPage(kategori);
        }

        private void menuRemove_Click(object sender, EventArgs e)
        {
            if (kategori == null)
                return;

            if (MessageBox.Show("Remove " + kategori.Kategori + "?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                DeleteCurrentCategory();    
        }
        
    }
}